var express = require('express');
var router = express.Router();
const dbExec = require('../postgreDB/config');
const AIFunc = require('./chessAI.js');

/* GET home page. */
router.get('/', function (req, res, next) {
  //get请求中query代表前端参数对象，post请求中body代表参数对象
  res.render('index', { title: 'Express' });
});

router.post("/createRoom", async (req, res, next) => {
  let data = req.body;
  let res1 = await dbExec(`select * from rooms where room='${data.room}'`);
  if (res1.rows.length) return res.status(200).send({
    code: 500,
    msg: '房间已存在'
  })
  let userId = Math.random().toString(32).substr(-4);
  await dbExec(`insert into rooms(room,userid1) values('${data.room}','${userId}')`)
  res.status(200).send({
    code: 200,
    id: userId
  });
});
router.post("/insertRoom", async (req, res, next) => {
  let data = req.body;
  /* let res1 = await dbExec(`select * from rooms where room='${data.room}'`);
  if (res1.rows.length == 0) return res.status(200).send({
    code: 500,
    msg: '房间不存在'
  })
  if (res1.rows[0].userid2) return res.status(200).send({
    code: 500,
    msg: '房间无空位'
  }) */
  let userId = Math.random().toString(32).substr(-4);
  await dbExec(`update rooms set userid2='${userId}' where room='${data.room}'`)
  res.status(200).send({
    code: 200,
    id: userId
  });
});

router.get("/getRoom", async (req, res, next) => {
  let data = req.query;
  let res1 = await dbExec(`select * from rooms where room='${data.room}'`);
  if (res1.rows.length) res.status(200).send({
    code: 200,
    data: res1.rows[0]
  });
  else res.status(200).send({
    code: 500,
    msg: '房间不存在'
  })
});

router.get("/delRoom", async (req, res, next) => {
  let data = req.query;
  let res1 = await dbExec(`delete from rooms where room='${data.room}'`);
  res.status(200).send({
    code: 200,
  });
});

router.post("/AIFunc", async (req, res, next) => {
  let data = req.body;
  res.status(200).send({
    code: 200,
    data: AIFunc(data.camp,data.arr)
  });
});

module.exports = router;
